package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//套餐添加逻辑实现
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    //导入redis缓存链接池
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outputpath;

    //新增套餐
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        //获取套餐id
        if(checkgroupIds != null && checkgroupIds.length > 0) {
            //绑定套餐和检查组的多对多关系
            for (Integer checkgroupId : checkgroupIds) {
                //设置套餐与检查组的关系表
                setmealDao.setSetmealAndCheckGroup(setmealId, checkgroupId);
            }
            //完成数据库操作后需要将图片名称保存到redis
            //!!!!!!!!!!!!!!用完jedis要释放回连接池
            Jedis resource = jedisPool.getResource();
            resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
            resource.close();
            //新增套餐后需要重新生成静态页面
            generateMobileStaticHtml();
//        setmealDao.add(setmeal);
//        //保存图片到reids
//        //获取图片名称
//        String img = setmeal.getImg();
//        //点击添加按钮时 保存图片名称到redis缓存 用于定时项目定时清理垃圾图片
//        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);
//
//        if(checkgroupIds != null && checkgroupIds.length > 0){
//            //绑定套餐和检查组的多对多关系
//            for (Integer checkgroupId : checkgroupIds) {
//                //设置套餐与检查组的关系表
//                setmealDao.setSetmealAndCheckGroup(setmeal.getId(),checkgroupId);
//                }
//        }
        }
    }

    //生成静态页面
    public void generateMobileStaticHtml(){
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = setmealDao.getSetmeal();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
    }

    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("setmeal", this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", dataMap);
        }
    }

    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try { // 加载模版文件
            Template template = configuration.getTemplate(templateName);
            // 生成数据
            File docFile = new File(outputpath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            // 输出文件
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }



    //分页查询
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> page = setmealDao.findPage(queryString);
        //返回总页数  和每页显示得数据
        return new PageResult(page.getTotal(), page.getResult());
    }

    //获取所有套餐信息
    @Override
    public List<Setmeal> getSetmeal() {
        return setmealDao.getSetmeal();
    }

    //通过id查询套餐信息.
    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    //删除套餐信息
    @Override
    public void delete(int id) {
        //删除套餐 需要先删除套餐与检查组的关系 在删除套餐
        setmealDao.deleteSetmealWithGroup(id);
        setmealDao.delete(id);
    }
    //根据套餐id查询关联检查组id
    @Override
    public List<Integer> findGroupIdsbyId(int id) {
        return setmealDao.findGroupIdsbyId(id);
    }
    //套餐编辑
    @Override
    public void edit(Setmeal setmeal, List<Integer> checkgroupIds) {
        //删除原有关系
        setmealDao.deleteSetmealWithGroup(setmeal.getId());
        //添加新关系
        for (Integer checkgroupId : checkgroupIds) {
            setmealDao.setSetmealAndCheckGroup(setmeal.getId(),checkgroupId);
        }
        //添加套餐信息.
        setmealDao.edit(setmeal);
    }
    //查询预约套餐数据 人数
    @Override
    public List<Map<String, Integer>> getSetmealCount() {

        return setmealDao.getSetmealCount();
    }
}

